<template>
    <div class="role-container">
        <FilterSearch
            :searchItems="searchItems"
            :showAddButton="showAddButton"
            @query="handleQuery"
            @add="handleAdd"
        />
        <AutoTable
            :tableData="tableData"
            :columns="columns"
            @operate="handleOperate"
        />
        <Pagination
            :total="total"
            :pageSize="pageSize"
            :currentPage="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
        <EditDialog
            ref="editDialogRef"
            :visible="editDialogVisible"
            :dialogType="editDialogType"
            :editItems="editItems"
            @successCallBack="editCallBack"
            @close="handleClose"
        />
        <TreeDialog
            ref="treeDialogRef"
            :visible="treeDialogVisible"
            :title="treeDialogTitle"
            :treeProps="treeProps"
            :loadNode="loadNode"
            :id="treeDialogId"
            :defaultCheckedKeys="defaultCheckedKeys"
            :changeFlag="changeFlag"
            :type="treeDialogType"
            @successCallBack="treeCallBack"
            @close="handleClose"
        />
    </div>
</template>
<script setup>
import './index.css';
import { reactive, ref, markRaw } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { View, Delete, Edit } from '@element-plus/icons-vue'

import FilterSearch from '@/components/filterSearch/index.vue';
import AutoTable from '@/components/autoTable/index.vue';
import Pagination from '@/components/pagination/index.vue';
import EditDialog from '@/components/editDialog/index.vue';
import TreeDialog from '@/components/treeDialog/index.vue';

import { roleApi, menuApi, permissionApi } from '@/api';
import { usePathStore } from '@/stores/paths';

// FilterSearch params
const searchItems = ref([
    {
      label: '角色编码',
      vModel: 'code',
      type: 'input',
      initialValue: ''
    },
    {
      label: '角色名称',
      vModel: 'name',
      type: 'input',
      initialValue: ''
    }
]);  
const showAddButton = ref(true);
const searchCache = ref({});

// AutoTable params
const tableData = ref([]);
const columns = ref([
    {
      label: '角色编码',
      prop: 'code',
      width: '140px'
    },
    {
      label: '角色名称',
      prop: 'name',
      width: '120px'
    },
    {
      label: '描述',
      prop: 'description',
    },
    {
      label: '操作',
      prop: 'operate',
      fixed: 'right',
      type: 'action',
      align: 'left',
      width: '140px',
      operate: [
        {label: '编辑角色权限', type: 'edit', icon: markRaw(Edit)}, 
        {label: '删除', type: 'delete', icon: markRaw(Delete)},
      ]
    }

]);

// Pagination params
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// edit Dialog params
const editDialogVisible = ref(false);
const editDialogType = ref('add');
const editItems = ref([
    {
      label: 'id',
      vModel: '_id',
      type: 'forbidden',
      initialValue: '',
    },
    {
      label: '角色编码',
      vModel: 'code',
      type: 'input',
      initialValue: '',
    },
    {
      label: '角色名称',
      vModel: 'name',
      type: 'input',
      initialValue: ''
    },
    {
      label: '描述',
      vModel: 'description',
      type: 'input',
      initialValue: ''
    }
]);  

// treeDialog params
const treeDialogVisible = ref(false);
const treeDialogTitle = ref('选择权限');
const treeDialogType = ref('updata');
const treeDialogId = ref('');
const defaultCheckedKeys = ref([]);
const changeFlag = ref(false);
const treeProps = ref({
    children: 'children',
    label: 'label',
    disabled: 'disabled',
    isLeaf: 'isLeaf'
});
const loadNode = ref(async (node, resolve) => {
    if (node.level === 0) {
        const res = await menuApi.getMenu({pageNum:1, pageSize:20, name: ''});
        const data = res.data.rows.map(item => ({
            id: item._id,
            label: item.name,
            disabled: true,
            children: item.children,
            secondToLast: item.component !== '',
            isLeaf: false
        }));
        resolve(data);
        return;
    }
    if (node.data.secondToLast) {
        const res = await permissionApi.getPermission({ menu_item: node.data.id });
        const data = res.data.rows[0].api_paths.map(item => ({
            id: `${res.data.rows[0]._id}:${item.split(':').slice(1).join(':')}`,
            label: item.split(':')[0],
            disabled: false,
            children: [],
            secondToLast: false,
            isLeaf: true
        }))
        resolve(data);
        changeFlag.value = !changeFlag.value;
        return;
    }else{
        const res = await menuApi.getMenu({ parentId: node.data.id });
        const data = res.data.rows.map(item => ({
            id: item._id,
            label: item.name,
            disabled: true,
            children: item.children,
            secondToLast: item.component !== '',
            isLeaf: false
        }));
        resolve(data);
        return;
    }
});

// filterSearch Api
const handleQuery = async (params) => {
    // 调用接口获取数据
    searchCache.value = params;
    const reqParams = {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        ...params
    }
    const res = await roleApi.getRole(reqParams);
    if (res.code === 200) {
      tableData.value = res.data.rows;
      total.value = res.data.total;
    }
};

// EditDialog Api
const handleAdd = () => {
    editDialogType.value = 'add';
    editDialogVisible.value = true;
};
const editCallBack = async (type, params) => {
    if (type === 'add') handleAddCallBack(params);
} 
const handleAddCallBack = async (params) => {
    const res = await roleApi.createRole(params);
    if (res.code === 200) {
        editDialogVisible.value = false;
        ElMessage.success('新增成功');
        handleQuery();
    }
}
const handleClose = () => {
    editDialogVisible.value = false;
    treeDialogVisible.value = false;
}

// Pagination Api
const handleSizeChange = (size) => {
    pageSize.value = size;
    handleQuery(searchCache.value);
};
const handleCurrentChange = (page) => {
    currentPage.value = page;
    handleQuery(searchCache.value);

};

// AutoTable Api
const handleOperate = (type, row) => {
    if (type === 'edit') {
      treeDialogTitle.value = '选择权限';
      treeDialogType.value = 'updata';
      defaultCheckedKeys.value = row.permissions;
      treeDialogId.value = row._id;
      treeDialogVisible.value = true;
    }
    else if (type === 'delete') {
      handleDelete(row);
    }
}
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定删除当前角色吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await roleApi.deleteRole(row._id)
      if (res.code === 200) {
        ElMessage({ type: 'success', message: '删除成功!' });
        handleQuery();
      }
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '取消删除!' })
    })
}

// treeDialog Api
const treeCallBack = async (id, permissionIds) => {
    const res = await roleApi.updateRolePermission(id, {permissionIds})
    if (res.code === 200) {
        ElMessage.success('更新成功');
        treeDialogVisible.value = false;
        handleQuery();
    }
}

</script>